<template>
  <!-- 角色列表组件 -->
  <div class="role-list">
    <!-- 头部路径导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>权限管理</el-breadcrumb-item>
      <el-breadcrumb-item>角色列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 角色列表数据 -->
    <el-card class="box-card">
      <el-button
        type="primary"
        size="default"
        @click="dialogAddRoleVisible = true"
        >添加角色</el-button
      >
      <div class="role-list-table">
        <el-table
          :data="roleList"
          border
          style="width: 100%"
          :stripe="true"
          ref="roleListTable"
        >
          <el-table-column prop="" label="" width="48" type="expand">
            <template slot-scope="props" >
              <div class="autho-view" v-if="props.row.children.length > 0">
                <el-row
                  class="expand-row"
                  v-for="item1 in props.row.children"
                  :key="item1.id"
                >
                  <el-col :span="6">
                    <el-tag
                      
                      closable
                      effect="dark"
                      @close="deleteAuthority(props.row.id, item1.id)"
                    >
                      {{ item1.authName }}
                    </el-tag>
                    <i class="el-icon-caret-right"></i>
                  </el-col>
                  <el-col :span="18" class="expand-col-right">
                    <el-col
                      :span="24"
                      v-for="item2 in item1.children"
                      :key="item2.id"
                      class="expand-col24-right"
                    >
                      <el-col :span="6">
                        <el-tag
                          closable
                          effect="dark"
                          type="success"
                          @close="deleteAuthority(props.row.id, item2.id)"
                        >
                          {{ item2.authName }}
                        </el-tag>
                        <i class="el-icon-caret-right"></i>
                      </el-col>
                      <el-col :span="18" style="text-align: left">
                        <el-tag
                          closable
                          effect="dark"
                          type="warning"
                          v-for="item3 in item2.children"
                          :key="item3.id"
                          @close="deleteAuthority(props.row.id, item3.id)"
                        >
                          {{ item3.authName }}
                        </el-tag>
                      </el-col>
                    </el-col>
                  </el-col>
                </el-row>
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="" label="#" width="48" type="index">
          </el-table-column>
          <el-table-column prop="roleName" label="角色名称"> </el-table-column>
          <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="editRole(scope.row.id)"
                >编辑</el-button
              >
              <el-button
                size="mini"
                type="danger"
                icon="el-icon-delete"
                @click="deleteRole(scope.row.id)"
                >删除</el-button
              >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="assignAuthority(scope.row.id)"
                >分配权限</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </div>
    </el-card>

    <!-- 添加角色弹出层 -->
    <el-dialog
      title="添加角色"
      :visible.sync="dialogAddRoleVisible"
      class="add-role-dialog"
    >
      <el-form
        :model="addRoleForm"
        :rules="addRoleFormRules"
        ref="addRoleForm"
        class="demo-ruleForm"
        :label-position="'left'"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="addRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="addRoleForm.roleDesc"></el-input>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button @click="dialogAddRoleVisible = false">取消</el-button>
          <el-button type="primary" @click="addRoleSubmit('addRoleForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 编辑角色弹出层 -->
    <el-dialog
      title="编辑角色"
      :visible.sync="dialogEditRoleVisible"
      class="edit-role-dialog"
    >
      <el-form
        :model="editRoleForm"
        :rules="addRoleFormRules"
        ref="editRoleForm"
        class="demo-ruleForm"
        :label-position="'left'"
        label-width="80px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="editRoleForm.roleName"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="roleDesc">
          <el-input v-model="editRoleForm.roleDesc"></el-input>
        </el-form-item>
        <el-form-item style="text-align: right">
          <el-button @click="dialogEditRoleVisible = false">取消</el-button>
          <el-button type="primary" @click="editRoleSubmit('editRoleForm')"
            >确定</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <!-- 分配权限弹出层 -->
    <el-dialog title="分配权限" :visible.sync="dialogAssignAuthorityVisible">
      <el-tree
        :data="authorityList"
        ref="authorityTree"
        show-checkbox
        node-key="id"
        :default-checked-keys="authorityIdArr"
        :default-expand-all="true"
        :props="authorityTreeProps"
        :check-strictly="false"
        class="authority-tree"
      >
      </el-tree>

      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogAssignAuthorityVisible = false"
          >取 消</el-button
        >
        <el-button type="primary" @click="assignAuthoritySubmit()"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    return {
      //角色列表数据
      roleList: [],
      //权限列表数据
      authorityList: [],
      //权限树属性设置
      authorityTreeProps: {
        children: "children",
        label: "authName",
      },
      authorityIdArr: [],
      //控制添加角色弹出框显示
      dialogAddRoleVisible: false,
      //控制编辑角色弹出框显示
      dialogEditRoleVisible: false,
      //控制分配权限弹出窗
      dialogAssignAuthorityVisible: false,
      //加载层参数配置
      loadingConfig: {
        target: "body",
        fullscreen: true,
        spinner: "el-icon-loading",
        background: "rgba(0, 0, 0, 0.1)",
        text: "拼命加载中",
      },
      //添加角色表单数据
      addRoleForm: {
        roleName: "", //角色名
        roleDesc: "", //角色描述
      },
      //添加角色表单验证规则
      addRoleFormRules: {
        roleName: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          {
            min: 1,
            max: 20,
            message: "角色名长度在 1 到 20 个字符",
            trigger: "blur",
          },
        ],
        roleDesc: [
          { required: true, message: "请输入角色描述", trigger: "blur" },
        ],
      },
      //编辑角色表单数据
      editRoleForm: {
        roleId: null, //角色ID
        roleName: "", //角色名
        roleDesc: "", //角色描述
      },
      //正在操作权限对应的ID
      operatingAuthorityId: null,
    };
  },
  methods: {
    renderRoleList(cb) {
      //渲染角色列表
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      this.$axios
        .get("/roles")
        .then((res) => {
          if (res.meta.status == 200) {
            //给每个角色添加index属性
            res.data.forEach((item, index) => {
              item["index"] = index + 1;
            });
            this.roleList = res.data;
            //关闭加载层
            this.$nextTick(() => {
              loading.close();
            });
            //执行回调函数
            if (cb) {
              cb();
            }
          } else {
            //关闭加载层
            this.$nextTick(() => {
              loading.close();
            });
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
          //请求失败
          this.$message.error(error);
        });
    },
    addRoleSubmit(formName) {
      //添加角色
      this.$refs[formName].validate((valid) => {
        if (valid) {
          //打开加载层
          var loading = this.$loading.service(this.loadingConfig);
          //发起添加角色请求
          this.$axios
            .post("/roles", {
              roleName: this.addRoleForm.roleName,
              roleDesc: this.addRoleForm.roleDesc,
            })
            .then((res) => {
              if (res.meta.status == 201) {
                //关闭加载层
                this.$nextTick(() => {
                  loading.close();
                });
                //关闭弹出层
                this.dialogAddRoleVisible = false;
                //提示成功信息
                this.$message.success(res.meta.msg);
                //重新渲染角色列表
                this.renderRoleList();
                //重置添加角色表单
                this.$refs[forName].resetFields();
                this.addRoleForm.roleName = "";
                this.addRoleForm.roleDesc = "";
              } else {
                //关闭加载层
                this.$nextTick(() => {
                  loading.close();
                });
                //提示错误信息
                this.$message.error(res.meta.msg);
              }
            })
            .catch((error) => {
              //关闭加载层
              this.$nextTick(() => {
                loading.close();
              });
              //请求失败
              this.$message.error(error);
            });
        }
      });
    },
    editRole(id) {
      //获取要编辑角色的信息
      this.getRoleInfo(id, () => {
        //打开编辑角色信息弹出框
        this.dialogEditRoleVisible = true;
      });
    },
    editRoleSubmit(forName) {
      //编辑角色提交
      this.$refs[forName].validate((valid) => {
        if (valid) {
          //打开加载层
          var loading = this.$loading.service(this.loadingConfig);
          //发起请求
          this.$axios
            .put("/roles/" + this.editRoleForm.roleId, {
              roleName: this.editRoleForm.roleName,
              roleDesc: this.editRoleForm.roleDesc,
            })
            .then((res) => {
              if (res.meta.status == 200) {
                //关闭加载层
                this.$nextTick(() => {
                  loading.close();
                });
                //关闭弹出层
                this.dialogEditRoleVisible = false;
                //提示成功信息
                this.$message.success(res.meta.msg);
                //重新渲染角色列表
                this.renderRoleList();
                //重置编辑角色表单
                this.$refs[forName].resetFields();
                this.editRoleForm.roleId = null;
                this.editRoleForm.roleName = null;
                this.editRoleForm.roleDesc = null;
              } else {
                //关闭加载层
                this.$nextTick(() => {
                  loading.close();
                });
                //提示错误信息
                this.$message.error(res.meta.msg);
              }
            })
            .catch((error) => {
              //关闭加载层
              this.$nextTick(() => {
                loading.close();
              });
              //请求失败
              this.$message.error(error);
            });
        }
      });
    },
    deleteRole(id) {
      //调用确认弹框
      this.$confirm("此操作将永久删除该角色，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        //点击确定执行删除角色
        this.deleteRoleSubmit(id);
      });
    },
    deleteRoleSubmit(id) {
      //根据ID删除角色
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起删除请求
      this.$axios
        .delete("/roles/" + id)
        .then((res) => {
          if (res.meta.status == 200) {
            //关闭加载层
            this.$nextTick(() => {
              loading.close();
            });
            //提示成功信息
            this.$message.success(res.meta.msg);
            //重新渲染角色列表
            this.renderRoleList();
          } else {
            //关闭加载层
            this.$nextTick(() => {
              loading.close();
            });
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
          //请求失败
          this.$message.error(error);
        });
    },
    assignAuthority(id) {
      //重置当前权限ID组
      this.authorityIdArr = [];
      //更新待编辑的角色ID
      this.editRoleForm.roleId = id;
      //获取权限树
      this.getAuthorityList("tree", () => {
        //获取最新角色列表
        this.renderRoleList(() => {
          //根据角色ID查询当前所拥有的权限
          var role = this.roleList.filter((item) => {
            return item.id == id;
          });
          console.log(role);
          var that = this;
          if (role[0].children.length > 0) {
            findAllId(role[0].children);
          }

          function findAllId(arr) {
            if (!arr) {
              return;
            }
            arr.forEach((item) => {
              if (item.children) {
                return findAllId(item.children);
              } else {
                that.authorityIdArr.push(item.id);
              }
            });
          }
          //打开分配权限弹出层
          this.dialogAssignAuthorityVisible = true;
          //重新渲染权限选中
          if (this.$refs["authorityTree"]) {
            this.$refs["authorityTree"].setCheckedKeys(this.authorityIdArr);
          }
        });
      });
    },
    assignAuthoritySubmit() {
      //分配权限提交
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //获取选中的权限列表
      var rids = this.$refs["authorityTree"].getCheckedKeys().join(",");
      console.log(rids);
      console.log(this.editRoleForm.roleId);
      //发起请求
      this.$axios
        .post("/roles/" + this.editRoleForm.roleId + "/rights", {
          rids: rids,
        })
        .then((res) => {
          if (res.meta.status == 200) {
            //关闭加载层
            this.$nextTick(() => {
              loading.close();
            });
            //关闭弹出层
            this.dialogAssignAuthorityVisible = false;
            //提示成功信息
            this.$message.success(res.meta.msg);
            //重新渲染角色列表
            this.renderRoleList();
          } else {
            //关闭加载层
            this.$nextTick(() => {
              loading.close();
            });
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
          //请求失败
          this.$message.error(error);
        });
    },
    deleteAuthority(roleId, authoId) {
      //更新当前所操作的角色ID
      // this.editRoleForm.roleId = roleId
      //更新当前操作权限的ID
      // this.operatingAuthorityId = authoId;
      //调用确认弹框
      this.$confirm("此操作将永久删除该权限，是否继续？", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          //点击确定执行删除权限
          this.deleteAuthoritySubmit(roleId, authoId);
        })
        .catch(() => {});
    },
    deleteAuthoritySubmit(roleId, authoId) {
      //删除角色指定权限
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起请求
      this.$axios
        .delete("/roles/" + roleId + "/rights/" + authoId)
        .then((res) => {
          if (res.meta.status == 200) {
            //提示成功信息
            this.$message.success(res.meta.msg);
            //重新渲染角色列表
            this.renderRoleList();
          } else {
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          //请求失败
          this.$message.error(error);
        })
        .finally(() => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
        });
    },
    getRoleInfo(id, cb) {
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //根据ID查找角色信息
      this.$axios
        .get("/roles/" + id)
        .then((res) => {
          if (res.meta.status == 200) {
            ///关闭加载层
            this.$nextTick(() => {
              loading.close();
            });
            //获取返回数据
            this.editRoleForm.roleId = res.data.roleId;
            this.editRoleForm.roleName = res.data.roleName;
            this.editRoleForm.roleDesc = res.data.roleDesc;
            //执行成功后的回调函数
            if (cb) {
              cb();
            }
          } else {
            ///关闭加载层
            this.$nextTick(() => {
              loading.close();
            });
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
          //请求失败
          this.$message.error(error);
        });
    },
    getAuthorityList(type, cb) {
      //获取权限列表
      //打开加载层
      var loading = this.$loading.service(this.loadingConfig);
      //发起请求
      this.$axios
        .get("/rights/" + type)
        .then((res) => {
          if (res.meta.status == 200) {
            //关闭加载层
            this.$nextTick(() => {
              loading.close();
            });
            this.authorityList = res.data;
            //执行回调函数
            if (cb) {
              cb();
            }
          } else {
            //关闭加载层
            this.$nextTick(() => {
              loading.close();
            });
            //提示错误信息
            this.$message.error(res.meta.msg);
          }
        })
        .catch((error) => {
          //关闭加载层
          this.$nextTick(() => {
            loading.close();
          });
          //请求失败
          this.$message.error(error);
        });
    }
  },
  mounted() {
    //模板挂载完成后渲染数据
    this.renderRoleList();
  },
};
</script>

<style lang="less">
.role-list-table {
  margin-top: 15px;
  table {
    td,
    th {
      font-size: 12px !important;
    }
    .autho-view {
      border: 1px solid #efefef;
    }
    .expand-row {
      display: flex;
      align-items: center;
      border-bottom: 1px solid #efefef;
      &:last-of-type {
        border-bottom: none;
      }
      .el-col {
        text-align: center;
      }
      .expand-col-right {
        border-left: 1px solid #efefef;
      }
      .expand-col24-right {
        display: flex;
        align-items: center;
        border-bottom: 1px solid #efefef;
        &:last-of-type {
          border-bottom: none;
        }
      }
      .el-tag {
        margin: 5px 10px 5px 0;
      }
    }
    .el-collapse {
      border: none;
      .el-collapse-item {
        .el-collapse-item__header {
          background-color: transparent;
          border-bottom: none;
        }
      }
    }
  }
}
</style>